package com.offcn.file.controller;

import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.file.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("file")
public class UploadController {

    @Value("${file_server_url}")
    private String file_server_url;

    /**
     * 文件上传的方式必须是  POST 请求 ，参数的类型：MultipartFile
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file){

        // 文件名
        String filename = file.getOriginalFilename();
        // 文件扩展名
        String extension = StringUtils.getFilenameExtension(filename);

//        String substring = filename.substring(filename.lastIndexOf(".") + 1);

        try {
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:fdfs_client.conf");
            String path = fastDFSClient.uploadFile(file.getBytes(), extension);
            String filePath = file_server_url + path;
            return new Result(true, StatusCode.OK,filePath,"文件上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"文件上传失败");
        }
    }
}
